import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lcapp/api/interface/comcon_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/data/comment_data_entity.dart';
import 'package:lcapp/data/lc_video_data_entity.dart';
import 'package:lcapp/model/refresh/refresh.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:lcapp/page/home/comment_item.dart';

class HomeCommentPage extends StatefulWidget {
  final LcVideoDataEntity? entity;
  const HomeCommentPage({Key? key, this.entity}) : super(key: key);

  @override
  _HomeCommentPageState createState() => _HomeCommentPageState();
}

class _HomeCommentPageState extends State<HomeCommentPage> {

  TextEditingController controller = TextEditingController();
  FocusNode focusNode = FocusNode();
  int pageNum = 1;
  int pageSize = 10;
  int total = 0;
  int replyId = 0;
  String hintText = '请输入您的评论';
  List<CommentDataEntity> comments = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getComments();
  }

  getComments()async{
    ResponseData res = await CommonAPI.getCommentList(widget.entity!.id!,pageNum,pageSize);
    if(res.code==200){
      if(pageNum==1){
        comments.clear();
      }
      setState(() {
        total = res.total!;
        print('total================' + total.toString());
        widget.entity?.comment = total;
        List arr = res.data??[];
        for (var element in arr) {
          CommentDataEntity dataEntity = CommentDataEntity().fromJson(element);
          dataEntity.replies = [];
          comments.add(dataEntity);
        }
      });
    }

  }
  saveComment()async{
    if(controller.text.isEmpty){
      showToast('请输入评论内容');
      return;
    }
    ResponseData res;
    showLoading();
    if(replyId!=0){
      res = await CommonAPI.saveCommentReply(replyId,controller.text);
    }else{
      res = await CommonAPI.saveComment(widget.entity!.id!, 1, controller.text);
    }
    hideLoading();
    if(res.code==200){
      showToast('发布评论成功');
      setState(() {
        replyId = 0;
        hintText = '请输入您的评论';
      });
      controller.text='';
      pageNum=1;
      getComments();
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        if(controller.text.trim().isEmpty){
          replyId = 0;
          hintText = '请输入您的评论';
        }
        FocusScope.of(context).requestFocus(FocusNode());
        SmartDialog.dismiss();
      },
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: GestureDetector(
          onTap: (){
            if(controller.text.trim().isEmpty){
              replyId = 0;
              hintText = '请输入您的评论';
            }
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Container(
            margin: EdgeInsets.only(top: 0.3.sh),
            height: 0.7.sh,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20.w)
            ),
            padding: EdgeInsets.only(top: 30.w,bottom: 30.w+ScreenUtil().bottomBarHeight),
            child: Column(
              children: [
                Container(
                  padding: EdgeInsets.only(left: 30.w,right: 30.w,bottom: 30.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('$total条评论',style: TextStyle(
                          color: Colors.black,
                          fontSize: 30.sp,
                          fontWeight: FontWeight.w500
                      ),),
                      GestureDetector(
                        onTap: (){
                          hintText = '请输入您的评论';
                          FocusScope.of(context).requestFocus(FocusNode());
                          SmartDialog.dismiss();
                        },
                        child: Icon(Icons.close,size: 40.w,),
                      )
                    ],
                  ),
                ),
                Expanded(child: Container(
                  padding: EdgeInsets.only(left: 30.w,right: 30.w),
                  child: EasyRefresh(
                    header: myRefreshHeader(),
                    footer: myRefreshFooter(),
                    onRefresh: ()async{
                      pageNum=1;
                      getComments();
                    },
                    onLoad: ()async{
                      pageNum++;
                      getComments();
                    },
                    child: ListView.builder(
                        padding: EdgeInsets.zero,
                        itemCount: comments.length,
                        itemBuilder: (context,index){
                          return CommentItem(entity: comments[index],commentFun: (cid,cName){
                            replyId = cid;
                            FocusScope.of(context).requestFocus(focusNode);
                            setState(() {
                              hintText = '回复@' + cName;
                            });
                          },);
                        }
                    ),
                  ),
                )),
                Container(
                  height: 1,
                  margin: EdgeInsets.only(bottom: 20.w,),
                  color: Color(0xffE9E8E9),
                ),
                Container(
                  padding: EdgeInsets.only(left: 30.w,right: 30.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(child: Container(
                        height: 80.w,
                        child: TextField(
                          controller: controller,
                          focusNode: focusNode,
                          textInputAction: TextInputAction.done,
                          maxLines: 1,
                          autocorrect: true,
                          autofocus: false,
                          decoration:  InputDecoration(
                            contentPadding: EdgeInsets.only(left: 17.w),
                            hintText: hintText,
                            hintStyle: TextStyle(
                              color: const Color(0xFFAEAEAE),
                              fontSize: 26.sp,
                              fontWeight: FontWeight.w500,
                            ),
                            counterText: "",
                            border: const OutlineInputBorder(
                                borderSide: BorderSide.none,
                                borderRadius: BorderRadius.all(Radius.circular(100))
                            ),
                            fillColor: Color(0xffF7F7F7),
                            filled: true,
                          ),
                          onChanged: (val){
                            setState(() {});
                          },
                        ),
                      )),
                      SizedBox(width: 20.w,),
                      GestureDetector(
                        onTap: (){
                          FocusScope.of(context).requestFocus(FocusNode());
                          if(controller.text.trim().isEmpty){
                            showToast('请输入评论');
                            return;
                          }
                          saveComment();
                        },
                        child: Container(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              // Icon(Icons.send,size: 40.w,color: Color(0xffEA6B2B):Color(0xff333333),),
                              Image.asset(controller.text!=null && controller.text.isNotEmpty ?"assets/home/send.png":"assets/home/send_gray.png",width: 30.w,),
                              SizedBox(height: 10.w,),
                              Text('发送',style: TextStyle(color:controller.text!=null && controller.text.isNotEmpty ? Color(0xffEA6B2B):Color(0xff333333),fontSize: 20.sp),)
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
